package com.acme.service.network;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

import com.acme.exceptions.ConnectionLostException;

public class BankClient {

	private static Socket requestSocket;
	
	private static BufferedReader brFromConsole;
	
	
	private static String messageFromConsole;
	private static String messageFromServer;
	
	static void startClient() throws ConnectionLostException{
		try {
			requestSocket = new Socket("127.0.0.1",2013);
			
			InputStreamReader isrFromConsole = new InputStreamReader(System.in);
			
			brFromConsole = new BufferedReader(isrFromConsole);
 			
		
			ObjectOutputStream oos = new ObjectOutputStream(requestSocket.getOutputStream());
			ObjectInputStream ois = new ObjectInputStream(requestSocket.getInputStream());
			
			do {
				messageFromConsole = brFromConsole.readLine();
				oos.writeObject(messageFromConsole);
				messageFromServer = (String)ois.readObject();
				if (messageFromServer == null) {
					break;
				}
				System.out.println(messageFromServer);
			} while ( !"Disconnected".equals(messageFromServer));
			
			brFromConsole.close();
			requestSocket.close();
			
		} catch (IOException e) {
			throw new ConnectionLostException("Connection with server lost " +
					"or not established");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		try {
			startClient();
		} catch (ConnectionLostException e) {
			System.out.println(e.getMessage());
		}
	}
}
